<template>
  <div class="app-container">
    <div class="data-tree">
      <el-button
        size="small"
        type="info"
        icon="el-icon-sort"
        @click="toggleExpandAll"
      >
        展开/折叠
      </el-button>
      <el-divider />
      <el-tree
        ref="tree"
        node-key="id"
        highlight-current
        accordion
        :indent="0"
        :expand-on-click-node="false"
        :default-expand-all="expanded"
        :props="defaultProps"
        :data="tableData1"
        @current-change="changeTree"
        @node-click="handleTreeNodeClick"
      >
        <span slot-scope="{ node, data }" class="custom-tree-node">
          <i class="folder"></i>
          <span
            class="label"
            :title="data.idx ? `${data.idx} ${node.label}` : node.label"
          >
            {{ data.idx ? `${data.idx} ${node.label}` : node.label }}
          </span>
        </span>
      </el-tree>
    </div>
    <div class="data-main">
      <div style="display:flex; justify-content: space-between;align-items:center">
        <el-row class="clearfix" style="margin: 0px 0px 15px 0px">
          <el-button type="primary" @click="addkyDirectorys">创建文件夹</el-button>
          <el-button
            type="primary"
            icon="el-icon-download"
            :disabled="selectionIds.length == 0"
            @click="downloadFileAll()"
          >批量下载</el-button>
          <el-button
            v-if="folderId && showUpLoad"
            type="warning"
            @click="upload.open = true"
          >上传</el-button>
        </el-row>
      </div>

      <el-table
        class="table-box"
        v-loading="listLoading"
        :data="tableData"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column label="名称">
          <template slot-scope="{ row }">
            <!-- 判断是文件夹还是文件 -->
            <el-link v-if="!row.fileType" :underline="false" @click="jumpFolder(row.id)">
              <img src="@/assets/static/folder.png" style="vertical-align: text-top" />
              {{ row.name }}
            </el-link>
            <span v-else>
              <el-link :underline="false" @click="jumpFolders(row)">
                <img src="@/assets/keyan/txt.png" style="vertical-align: text-top" />
                {{ row.name.substring(0,row.name.lastIndexOf("--"))}}
              </el-link>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="大小" align="center" width="120">
          <template slot-scope="scope">
            <span
              v-if="!scope.row.fileType"
            >{{ scope.row.directorySize<1000? scope.row.directorySize +'M':scope.row.directorySize +'G' }}</span>
            <span
              v-if="scope.row.fileType"
            >{{ scope.row.fileSize<1000? scope.row.fileSize +'M':scope.row.fileSize +'G' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建者" align="center" prop="createBy" width="120" />
        <el-table-column label="更新时间" align="center" prop="createTime" width="170" />

        <el-table-column label="操作" align="center" :width="!folderId ? 320 : 320">
          <template slot-scope="scope">
            <el-button
              v-if="!folderId"
              type="text"
              size="small"
              style="color: #E6A23C"
              @click="quickPrint(scope.row)"
            >快捷打印</el-button>
            <el-button
              v-if="folderId"
              size="small"
              type="text"
              style="color: #E6A23C"
              @click="print(scope.row)"
              >打印</el-button>
            <el-button
              v-if="showBtn"
              type="text"
              size="small"
              style="color: #3B95FF"
              @click="oneQuanxuan(scope.row)"
            >设置权限</el-button>
            <el-button
              v-if="showBtn"
              type="text"
              size="small"
              style="color: #3B95FF"
              @click="moveQuanxian(scope.row)"
            >移动</el-button>
            <el-button
              type="text"
              size="small"
              style="color: #45B177"
              @click="downloadFile(scope.row)"
            >下载</el-button>
            <el-button
              v-if="scope.row.fileType || showBtn"
              type="text"
              size="small"
              style="color: #45B177"
              @click="editFile(scope.row)"
            >重命名</el-button>
            <el-button
              v-if="showBtn"
              type="text"
              size="small"
              style="color: #E86565"
              @click="delQuanxian(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 快捷打印 -->
      <el-dialog
        width="550px"
        :title="dayinName"
        :visible.sync="printDialog.visible"
        :close-on-click-modal="false"
        :show-close="false"
      >
        <el-tree
          ref="printTree"
          node-key="id"
          highlight-current
          default-expand-all
          :expand-on-click-node="false"
          show-checkbox
          :props="treeProps"
          :data="treeData"
          @check="handleCheckChange"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="printDialog.visible = false">取 消</el-button>
          <el-button
            type="primary"
            :disabled="printDialog.checkedKeys.length === 0"
            @click="printClick"
          >打 印</el-button>
        </div>
      </el-dialog>
      <!-- 编辑文件名 -->
      <el-dialog
        title="文件夹重命名"
        :visible.sync="centerDialogVisible5"
        width="25%"
        style="border-radius:10px"
        center
      >
        <div style="width:100%;height:auto;padding:2%;border-radius:5px">
          <el-input v-model="titlename"></el-input>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="centerDialogVisible5 = false">取消</el-button>
          <el-button type="primary" @click="sureName()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 上传文件 -->
      <el-dialog
        title="文件"
        :visible.sync="upload.open"
        width="30%"
        style="border-radius:10px"
        :close-on-click-modal="false"
        :show-close="false"
      >
        <el-form label-width="80px" ref="form" :model="form" :rules="rules">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" clearable placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="完成人员" prop="userIds">
            <el-select
              style="width: 100%"
              v-model="form.userIds"
              filterable
              multiple
              clearable
              placeholder="请选择完成人员"
            >
              <el-option
                v-for="item in peopleList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择文件" prop="file">
            <el-upload
              ref="upload"
              :headers="upload.headers"
              :action="upload.action"
              :data="upload.params"
              :auto-upload="false"
              :limit="1"
              :before-upload="beforeUpload"
              :on-change="handleChange"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
            >
              <el-button slot="trigger" type="primary">点击上传文件</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeUploadDialog">取 消</el-button>
          <el-button type="primary" @click="handleUpload">提 交</el-button>
        </span>
      </el-dialog>
      <!-- 移动目录弹框 -->
      <el-dialog
        title="移动目录"
        :visible.sync="centerDialogVisible2"
        width="35%"
        v-if="centerDialogVisible2"
        center
        @close="close2()"
      >
        <el-form
          label-width="80px"
          :model="formLabelAlign2"
          ref="formLabelAlign2"
          class="aside"
          style="height:600px; overflow: auto;"
        >
          <el-form-item>
            <el-tree
              ref="tree"
              showIcon="true"
              default-expand-all
              :highlight-current="true"
              :data="keyanList"
              :props="defaultProps"
              @current-change="changeTreeMulu"
            ></el-tree>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close2()">取 消</el-button>
          <el-button type="primary" @click="sure2()" :disabled="sure2Disabled">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 权限弹框 -->
      <el-dialog
        :title="'《'+titlename +'》'+'权限人员'"
        :visible.sync="centerDialogVisible"
        width="40%"
        center
        @close="close()"
      >
        <el-form label-width="80px" :model="formLabelAlign" ref="formLabelAlign">
          <el-form-item label="可见权限" prop="assessUserType">
            <el-cascader
              style="margin-left:15px;width:90%"
              :show-all-levels="false"
              v-model="formLabelAlign.UserId1"
              placeholder="请选择"
              :options="this.user"
              :props="{ multiple: true,label: 'label',value: 'value', checkStrictly: false }"
              @change="handleNodeClick1"
            ></el-cascader>
          </el-form-item>
          <el-form-item
            style="margin-top:5%"
            label="上传权限"
            prop="assessUserType"
            v-if="lookquanxianPeople==1?true:false"
          >
            <el-cascader
              style="margin-left:15px;width:90%"
              :show-all-levels="false"
              v-model="formLabelAlign.UserId2"
              placeholder="请选择"
              :options="this.user"
              :props="{ multiple: true,label: 'label',value: 'value', checkStrictly: false }"
              @change="handleNodeClick2"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close()">取 消</el-button>
          <el-button type="primary" @click="sure()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
  
  <script>
import printJS from "print-js";
import { getUserId } from "@/api2/kaohe";
import { apiPeoList } from "@/api2/projectManagement/reporting";
import {
  getKeYanList,
  kyDirectory,
  addkyDirectory,
  deletekyDirectory,
  moveyDirectory,
  addDocument,
  deleteDocuments,
  movewenjian,
  getTreeShuaxin,
  dowLoadZip,
  printDocument
} from "@/api2/keyan";
import { getToken } from "@/utils/auth";
import { uploadUrl } from "@/const";
import { serverUrl } from "@/look";
import { Base64 } from "js-base64";
import { websock } from "@/websock";
const base_url = process.env.VUE_APP_BASE_APITwo;
export default {
  data() {
    const validator = (rule, value, callback) => {
      if (this.fileList.length == 0) {
        callback(new Error("文件不能为空"));
      } else {
        callback();
      }
    };
    return {
      expanded: true,
      printDialog: {
        visible: false,
        checkedKeys: []
      },
      dayinName: "",
      namelistShow: false,
      uploadUrl,
      quanxianId: "",
      oneQuanxianList: {},
      nameList: [],
      nameList1: [],
      titlename: "",
      selectionIds: [],
      peopleList: [],
      nameId: "",
      idsd: "",
      namePid: "",
      titleMap1: {
        addEquipment1: "新建文件夹名称",
        editEquipment1: "编辑文件夹名称"
      },
      dialogStatus: "",
      dialogStatus1: "",
      formLabelAlign1: {
        name: ""
      },
      form: { userIds: [] },
      rules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        file: [{ validator, trigger: "change" }]
      },
      user: [],
      defaultProps: {
        label: "name",
        children: "children",
        id: "id"
      },
      keyanList: [], //科研资料库树
      showBtn: false,
      sure2Disabled: true,
      upload: {
        headers: { Authorization: getToken(), platform: 'WEB' },
        action: base_url + "/common/upload",
        open: false,
        params: {}
      },
      formLabelAlign2: {
        mulu: "",
        dianjimulu: ""
      },
      formLabelAlign: {
        UserId1: [],
        UserId2: [],
        assessorUserId1: [],
        assessorUserId2: []
      },
      sss1: [],
      sss2: [],
      urrlList: [],
      centerDialogVisible: false,
      centerDialogVisible1: false,
      centerDialogVisible2: false,
      // centerDialogVisible3: false,
      centerDialogVisible4: false,
      centerDialogVisible5: false,
      lookquanxianPeople: 1,
      headers: { Authorization: getToken(), platform: 'WEB' },
      formInline: {},
      tableData: [],
      tableData1: [],
      listLoading: false,
      pageNum: 1,
      pageSize: 10,
      roleNames: "",
      peopleIds: "",
      total: 0,
      pids: "",
      folderId: undefined,
      showUpLoad: false,
      breadcrumbs: [{ name: "科研资料库" }],
      treeData: [],
      treeProps: { label: "name" },
      dialog: {
        visible: false,
        movedId: undefined,
        movedPid: undefined,
        toMoveId: undefined
      },
      printDialog: {
        visible: false,
        checkedKeys: []
      }
    };
  },
  created() {
    this.getuseList();
    this.getAllUser();
    this.getUserIds(); //获取用户基本信息
  },
  methods: {
    toggleExpandAll() {
      const treeNode = this.$refs.tree.store.nodesMap;
      for (let key in treeNode) {
        treeNode[key].expanded = !this.expanded;
      }
      this.expanded = !this.expanded;
    },
    //获取人员
    async getuseList() {
      const res = await websock.getContactList();
      const userList = [];
      for (let i = 0; i !== res.length; i++) {
        userList.push({
          value: i + "",
          label: res[i].name,
          children: []
        });
        for (let j = 0; j !== res[i].userList.length; j++) {
          userList[i].children.push({
            value: res[i].userList[j].uid,
            label: res[i].userList[j].name
          });
        }
      }
      this.user = userList;
    },
    //获取用户基本信息
    getUserIds() {
      setTimeout(() => {
        getUserId()
          .then(res => {
            this.quanxianId = res.data.id;
            if (res.code == 0) {
              if (res.data.roleName == "科研管理员") {
                this.getKeYanLists();
                this.roleNames = res.data.roleName;
                this.showBtn = true;
                this.namelistShow = true;
              } else {
                this.getKeYanLists(res.data.id);
                this.peopleIds = res.data.id;
                this.showBtn = false;
                this.namelistShow = false;
              }
            } else {
              console.log(error);
            }
          })
          .catch(e => {
            console.log(e);
          });
      }, 1);
    },
    // 获取所有人员id
    async getAllUser() {
      const res = await apiPeoList();
      this.peopleList = res.data;
      this.quanxianList = res.data;
    },
    renderTreeNode(data, index) {
      return data.map((v, i) => {
        const idx = index ? index + "." + (i + 1) : i + 1;
        this.$set(v, "idx", idx);
        if (v.children?.length) {
          v.children = this.renderTreeNode(v.children, v.idx);
        }
        return v;
      });
    },
    async getKeYanLists(e) {
      this.listLoading = true;
      if (!e) {
        const res = await getKeYanList();
        if (res.code == 0) {
          this.isAdmin = 1;
          res.data[0].children.forEach(item => {});
          this.tableData = res.data[0].children;
          this.tableData1 = this.renderTreeNode(res.data[0].children);
          this.keyanList = res.data[0].children;
          this.total = res.data[0].children.length;
        }
      } else {
        const params = {
          uploadUserIds: e,
          visibleUserIds: e
        };
        const res1 = await getKeYanList(params);
        if (res1.data[0].children == null) {
          this.tableData = [];
          this.tableData1 = [];
          this.total = 0;
        } else {
          this.isAdmin = 2;
          this.tableData = res1.data[0].children;
          this.tableData1 = this.renderTreeNode(res1.data[0].children);
          this.total = res1.data[0].children.length;
        }
      }
      setTimeout(() => {
        this.listLoading = false;
      }, 100);
    },

    //获取用户基本信息
    getUserIds1() {
      setTimeout(() => {
        getUserId()
          .then(res => {
            this.quanxianId = res.data.id;
            if (res.code == 0) {
              if (res.data.roleName == "科研管理员") {
                this.getKeYanLists1();
                this.roleNames = res.data.roleName;
                this.showBtn = true;
                this.namelistShow = true;
              } else {
                this.getKeYanLists1(res.data.id);
                this.peopleIds = res.data.id;
                this.showBtn = false;
                this.namelistShow = false;
              }
            } else {
              console.log(error);
            }
          })
          .catch(e => {
            console.log(e);
          });
      }, 1);
    },

    async getKeYanLists1(e) {
      this.listLoading = true;
      if (!e) {
        const res = await getKeYanList();
        if (res.code == 0) {
          this.isAdmin = 1;
          res.data[0].children.forEach(item => {});
          // this.tableData = res.data[0].children;
          this.tableData1 = this.renderTreeNode(res.data[0].children);
          // this.keyanList = res.data[0].children;
          // this.total = res.data[0].children.length;
        }
      } else {
        const params = {
          uploadUserIds: e,
          visibleUserIds: e
        };
        const res1 = await getKeYanList(params);
        if (res1.data[0].children == null) {
          // this.tableData = [];
          this.tableData1 = [];
          // this.total = 0;
        } else {
          this.isAdmin = 2;
          // this.tableData = res1.data[0].children;
          this.tableData1 = this.renderTreeNode(res1.data[0].children);
          // this.total = res1.data[0].children.length;
        }
      }
      setTimeout(() => {
        this.listLoading = false;
      }, 100);
    },
    handleTreeNodeClick({ id }) {
      console.log(id);
      // if (this.folderId === id) return;
      this.jumpFolder(id);
    },
    jumpFolder(id) {
      this.pids = id;
      if (this.roleNames == "科研管理员") {
        this.showUpLoad = true;
      } else {
        if (rows.uploadUserIds) {
          let idd = rows.uploadUserIds
            .split(",")
            .some(
              item =>
                item == JSON.parse(sessionStorage.getItem("loginUserinfo")).uid
            );
          if (idd == true) {
            this.showUpLoad = true;
          } else {
            this.showUpLoad = false;
          }
        }
      }
      this.getFolderList(id);
    },
    handleSelectionChange(val) {
      console.log(val);
      let arr = [];
      val.forEach(item => {
        if (item.fileType) {
          arr.push({ id: item.id, type: "2" });
        } else {
          arr.push({ id: item.id, type: "1" });
        }
      });
      console.log(arr);
      this.selectionIds = arr;
    },
    changeTree(rows) {
      console.log(rows);
      this.pids = rows.id;
      let name = rows.name;
      let ids = rows.id;
      // this.breadcrumbs.push({ name, ids });
      //   判断有无上传权限
      if (this.roleNames == "科研管理员") {
        this.showUpLoad = true;
      } else {
        if (rows.uploadUserIds) {
          let idd = rows.uploadUserIds
            .split(",")
            .some(
              item =>
                item == JSON.parse(sessionStorage.getItem("loginUserinfo")).uid
            );
          if (idd == true) {
            this.showUpLoad = true;
          } else {
            this.showUpLoad = false;
          }
        }
      }
      // this.getFolderList(ids);
    },
    // 在线预览pdf,doxc,xlsx...
    jumpFolders(rows) {
      if (rows.url) {
        window.open(
          serverUrl +
            "onlinePreview?url=" +
            encodeURIComponent(Base64.encodeURI(rows.url))
        );
      }
    },
    async getFolderList(id, idx) {
      this.folderId = id ? id : undefined;
      idx && this.breadcrumbs.splice(idx, this.breadcrumbs.length - 1);
      this.pageNum = 1;
      if (idx == 1) {
        this.getUserIds();
      } else {
        const res = await getTreeShuaxin({ id });
        if (res.code == 0) {
          if (res.data.children) {
            this.tableData = [...res.data.children, ...res.data.files];
          } else if (!res.data.children) {
            this.tableData = [...res.data.files];
          } else {
            this.tableData = [];
          }
        }
      }
    },
    //新建文件夹
    async addkyDirectorys() {
      this.$prompt(`请输入新文件夹名称`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputValidator: value => {
          if (!value) {
            return "名称不能为空！";
          }
          if (value.length > 10) {
            return "名称限制10个字以内！";
          }
        }
      })
        .then(async ({ value }) => {
          const kyDirectory = {
            pid: this.folderId || "0",
            type: 1,
            directorySize: 0,
            uploadUserIds: this.quanxianId,
            visibleUserIds: this.quanxianId,
            name: value
          };
          await addkyDirectory(kyDirectory);
          if (kyDirectory.pid == 0) {
            const res = await getTreeShuaxin({
              id: "d867c53ac0c54bf9336b8b2a2b4fc5a0"
            });
            if (res.code == 0) {
              if (res.data.children) {
                this.tableData = [...res.data.children, ...res.data.files];
              } else if (!res.data.children) {
                this.tableData = [...res.data.files];
              } else {
                this.tableData = [];
              }
              this.getKeYanLists1();
            }
          } else {
            const res = await getTreeShuaxin({
              id: kyDirectory.pid
            });
            if (res.code == 0) {
              if (res.data.children) {
                this.tableData = [...res.data.children, ...res.data.files];
              } else if (!res.data.children) {
                this.tableData = [...res.data.files];
              } else {
                this.tableData = [];
              }
              this.getKeYanLists1();
            }
          }
          if (res.code == 0) {
            if (res.data.children) {
              this.tableData = [...res.data.children, ...res.data.files];
            } else if (!res.data.children) {
              this.tableData = [...res.data.files];
            } else {
              this.tableData = [];
            }
            this.getKeYanLists1();
          }
        })
        .catch(() => {});
    },
    //文件夹重命名
    editFile(i) {
      console.log(i);
      this.nameId = i.id;
      this.namePid = i.pid;
      this.titlename = i.name;
      this.centerDialogVisible5 = true;
    },
    //确定重命名
    async sureName() {
      const operationType = 2;
      const kyDirectory = {
        id: this.nameId,
        pid: this.namePid,
        name: this.titlename
      };
      const res = await moveyDirectory(operationType, kyDirectory);
      this.listLoading = true;
      if (res.code == 0) {
        this.$message.success("修改成功");
        this.getKeYanLists1();
        const res = await getTreeShuaxin({ id: kyDirectory.pid });
        if (res.code == 0) {
          if (res.data.children) {
            this.tableData = [...res.data.children, ...res.data.files];
          } else if (!res.data.children) {
            this.tableData = [...res.data.files];
          } else {
            this.tableData = [];
          }
        }
        this.centerDialogVisible5 = false;
        this.listLoading = false;
      } else {
        this.$message.error(res.msg);
      }
    },
    //删除
    async delQuanxian(row) {
      this.$confirm("此操作将删除内容, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const isAdmin = true;
          const id = row.id;
          console.log(row);
          if (row.fileType) {
            // 删除文件
            deletekyDirectory(id).then(async res => {
              this.listLoading = true;
              if (res.code == 0) {
                this.$message.success("删除成功");
                this.listLoading = false;
                const res = await getTreeShuaxin({ id: row.directoryId });
                if (res.code == 0) {
                  console.log(res);
                  if (res.data.children) {
                    this.tableData = [...res.data.children, ...res.data.files];
                  } else if (!res.data.children) {
                    this.tableData = [...res.data.files];
                  } else {
                    this.tableData = [];
                  }
                }
              }
            });
          } else {
            // 删除文件夹
            deleteDocuments(id, isAdmin).then(async res => {
              if (res.code == 0) {
                this.$message.success("删除成功");
                this.getKeYanLists1();
                const res = await getTreeShuaxin({
                  id: row.pid,
                  isAdmin: true
                });
                if (res.code == 0) {
                  if (res.data.children) {
                    this.tableData = [...res.data.children, ...res.data.files];
                  } else {
                    this.tableData = [];
                  }
                }
                this.listLoading = false;
              }
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // upLoad() {
    //   this.centerDialogVisible3 = true;
    // },
    async handleSuccess(res, file) {
      console.log(res, file);

      if (res.code !== 0) {
        return this.$message.error(res.message);
      } else {
        this.urrlList.push({
          title: this.form.title,
          kyPersonId: this.form.userIds.join(),
          name: res.data.fileName,
          fileType: res.data.suffix,
          fileSize: res.data.size,
          url: res.data.url
        });
        console.log(this.urrlList);

        const isAdmin = this.isAdmin;
        const params = {
          isAdmin: isAdmin,
          directoryId: this.pids,
          kyFiles: this.urrlList ? this.urrlList : []
        };
        console.log(params);
        const resd = await addDocument(isAdmin, params);
        if (resd.code == 0) {
          this.$message.success("文件上传成功");
          this.urrlList = [];
          this.closeUploadDialog();
          const res = await getTreeShuaxin({ id: params.directoryId });
          if (res.code == 0) {
            if (res.data.children) {
              this.tableData = res.data.children;
            } else {
              this.tableData = [];
            }
          }
          if (this.roleNames == "科研管理员") {
            const res = await getTreeShuaxin({ id: params.directoryId });
            if (res.code == 0) {
              if (res.data.children) {
                this.tableData = [...res.data.children, ...res.data.files];
              } else if (!res.data.children) {
                this.tableData = [...res.data.files];
              } else {
                this.tableData = [];
              }
            }
            this.showUpLoad = true;
          } else {
            const params = {
              visibleUserIds: this.peopleIds,
              id: this.pids
            };
            const res = await getTreeShuaxin(params);
            if (res.code == 0) {
              if (res.data.children) {
                this.tableData = res.data.children;
              } else {
                this.tableData = [];
              }
            }
          }
        } else if (res.code != 0 && res.msg) {
          this.$message.error(res.msg);
        } else {
          this.$message.error("上传失败，请重试！");
        }
        // this.centerDialogVisible3 = false;
      }
    },
    handleRemove(file, fileList) {
      this.fileList = [];
      this.$refs.upload.clearFiles();
      this.$refs.form.validateField("file");
      console.log(file, fileList);
      this.urrlList = fileList;
      this.urrlList.forEach(item => {
        fileList.forEach(items => {
          if (items && items.url !== item.url) {
            const list = listArr.filter(item => item.url);
          }
        });
      });
      // fileList = fileList.filter(item => {
      //   return item.name !== file.name;
      // });
    },
    handleChange(file, fileList) {
      this.fileList = [file];
      this.$refs.form.validateField("file");
    },
    closeUploadDialog() {
      this.urrlList = [];
      this.fileList = [];
      this.$refs.upload.clearFiles();
      this.$refs.form.resetFields();
      this.upload.open = false;
    },
    // 快捷打印
    quickPrint({ id, name }) {
      this.dayinName = name;
      this.printDialog.visible = true;
      this.printDialog.checkedKeys = [];
      getTreeShuaxin({ id }).then(res => {
        console.log(res);
        if (res.code == 0) {
          if (res.data.children) {
            console.log([...res.data.children, ...res.data.files]);
            this.treeData = [...res.data.children, ...res.data.files];
          } else if (!res.data.children) {
            this.treeData = [...res.data.files];
          } else {
            this.treeData = [];
          }
        }
        this.traverseArr1(this.treeData);
        console.log(this.treeData);
        this.traverseArr(this.treeData);
      });
    },
    traverseArr(data) {
      data.forEach(item => {
        if (item.children) {
          item.children = [...item.children, ...item.files];
          this.traverseArr(item.children);
        }
      });
      return data;
    },
    traverseArr1(data) {
      data.forEach(item => {
        if (item.fileType) {
          item.name = item.name.substring(0, item.name.lastIndexOf("--"));
        } else {
          if (item.children) {
            if (item.files.length !== 0) {
              item.files.forEach(items => {
                console.log(items);
                items.name = items.name.substring(
                  0,
                  items.name.lastIndexOf("--")
                );
              });
              this.traverseArr1(item.children);
            }
          }
        }
      });
      return data;
    },
    handleCheckChange(data, checked) {
      console.log(data, checked);
      let arr = [];
      checked.checkedNodes.forEach(item => {
        if (!item.fileType) {
          arr.push({ id: item.id, type: "1" });
        } else {
          arr.push({ id: item.id, type: "2" });
        }
      });
      this.printDialog.checkedKeys = arr;
    },
    print(row) {
      console.log(row);
      let arr = [];
      if (!row.fileType) {
        arr.push({ id: row.id, type: "1" });
      } else {
        arr.push({ id: row.id, type: "2" });
      }
      this.printDialog.checkedKeys = arr;
      // this.printDialog.checkedKeys = [id];
      this.printClick();
    },
    async printClick() {
      let arr = this.printDialog.checkedKeys;
      const res = await printDocument(arr);
      console.log(res);
      printJS(res.data.url);
    },
    //上传
    beforeUpload(rawFile) {
      const isLt5M = rawFile.size / 1024 / 1024 < 20;
      if (!isLt5M) {
        this.$message.error("文件大小限制在 20MB 内!");
        return false;
      }
    },
    handleUpload() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          let { title, userIds } = this.form;
          userIds = userIds.join();
          this.$set(this.upload.params, "title", title);
          this.$set(this.upload.params, "userIds", userIds);
          this.$refs.upload.submit();
        }
      });
    },
    //移动
    moveQuanxian(row) {
      this.formLabelAlign2.dianjimulu = row;
      this.centerDialogVisible2 = true;
    },
    //选择目录
    changeTreeMulu(e) {
      this.sure2Disabled = false;
      this.formLabelAlign2.mulu = e;
    },
    //确定移动
    async sure2() {
      //   移动目录
      if (!this.formLabelAlign2.dianjimulu.fileType) {
        this.$confirm(
          "确定将" +
            "《" +
            (this.formLabelAlign2.dianjimulu.fileType
              ? this.formLabelAlign2.dianjimulu.name.substring(
                  0,
                  this.formLabelAlign2.dianjimulu.name.lastIndexOf("--")
                )
              : this.formLabelAlign2.dianjimulu.name) +
            "》" +
            "移动到" +
            "《" +
            this.formLabelAlign2.mulu.name +
            "》" +
            "目录下吗？",
          "是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(res1 => {
            this.listLoading = true;
            const operationType = 1;
            const kyDirectory = {
              operationType: 1,
              id: this.formLabelAlign2.dianjimulu.id,
              pid: this.formLabelAlign2.mulu.id
            };
            console.log(kyDirectory);
            if (
              this.formLabelAlign2.dianjimulu.id == this.formLabelAlign2.mulu.id
            ) {
              this.$message.error("无法移动到相同目录");
              return;
            }
            moveyDirectory(operationType, kyDirectory).then(async res => {
              if (res.code == 0) {
                this.$message.success("移动成功");
                this.getKeYanLists1();
                const res = await getTreeShuaxin({
                  id: this.formLabelAlign2.dianjimulu.pid
                });
                if (res.code == 0) {
                  if (res.data.children) {
                    this.tableData = [...res.data.children, ...res.data.files];
                  } else if (!res.data.children) {
                    this.tableData = [...res.data.files];
                  } else {
                    this.tableData = [];
                  }
                }
                // this.name = this.name2;
                this.centerDialogVisible2 = false;
              } else {
                this.$message.error(res.msg);
              }
            });
            this.listLoading = false;
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      } else if (this.formLabelAlign2.dianjimulu.fileType) {
        //   移动文件
        this.$confirm(
          "确定将" +
            "《" +
            (this.formLabelAlign2.dianjimulu.fileType
              ? this.formLabelAlign2.dianjimulu.name.substring(
                  0,
                  this.formLabelAlign2.dianjimulu.name.lastIndexOf("--")
                )
              : this.formLabelAlign2.dianjimulu.name) +
            "》" +
            "移动到" +
            "《" +
            this.formLabelAlign2.mulu.name +
            "》" +
            "目录下吗？",
          "是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(res1 => {
            this.listLoading = true;
            const kyFile = {
              operationType: 1,
              id: this.formLabelAlign2.dianjimulu.id,
              directoryId: this.formLabelAlign2.mulu.id
            };
            console.log(kyFile);
            if (
              this.formLabelAlign2.dianjimulu.id == this.formLabelAlign2.mulu.id
            ) {
              this.$message.error("无法移动到相同目录");
              return;
            }
            movewenjian(kyFile).then(async res => {
              if (res.code == 0) {
                this.$message.success("移动成功");
                this.getKeYanLists1();
                const res = await getTreeShuaxin({
                  id: this.formLabelAlign2.dianjimulu.directoryId
                });
                if (res.code == 0) {
                  if (res.data.children) {
                    this.tableData = [...res.data.children, ...res.data.files];
                  } else if (!res.data.children) {
                    this.tableData = [...res.data.files];
                  } else {
                    this.tableData = [];
                  }
                }
                // this.name = this.name2;
                this.centerDialogVisible2 = false;
              } else {
                this.$message.error(res.msg);
              }
            });
            this.listLoading = false;
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      }
    },
    //取消移动
    close2() {
      this.formLabelAlign2 = {
        mulu: "",
        dianjimulu: ""
      };
      this.sure2Disabled = true;
      this.centerDialogVisible2 = false;
    },
    //批量下载----------------------------------------------------------------
    downloadFileAll() {
      const params = this.selectionIds;
      this.$confirm("是否下载所有文件?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          dowLoadZip(params).then(res => {
            console.log(res);
            const a = document.createElement("a");
            a.style.display = "none";
            a.href = res.data.url;
            a.target = "_blank";
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //下载zip
    downloadFile(row) {
      console.log(row);
      if (!row.fileType) {
        let arr = [];
        arr.push({ id: row.id, type: "1" });
        const requestList = arr;
        console.log(requestList);
        this.$confirm("是否确认导出该文件夹下所有数据?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            dowLoadZip(requestList).then(res => {
              console.log(res);
              const a = document.createElement("a");
              a.style.display = "none";
              a.href = res.data.url;
              a.target = "_blank";
              document.body.appendChild(a);
              a.click();
              document.body.removeChild(a);
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      } else {
        this.$confirm("是否下载该文件?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(res => {
            let a = document.createElement("a");
            a.href = row.url;
            a.download = row.name.substring(0, row.name.lastIndexOf("--"));
            a.style.display = "none";
            document.body.appendChild(a);
            a.click();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      }
    },
    //单个权限
    oneQuanxuan(rows) {
      console.log(rows);
      this.oneQuanxianList = rows;
      let arr = [];
      arr.push(rows.id);
      this.idsd = Array.from(new Set(arr)).toString();
      if (rows.fileType) {
        this.titlename = rows.name.substring(0, rows.name.lastIndexOf("--"));
        this.lookquanxianPeople = 0;
      } else {
        this.titlename = rows.name;
        this.lookquanxianPeople = 1;
      }
      this.centerDialogVisible = true;
      let arr2 = [];
      let arr3 = [];
      //   上传权限
      this.quanxianList.forEach(item => {
        if (rows.uploadUserIds) {
          rows.uploadUserIds.split(",").forEach(items => {
            if (item.id == items) {
              arr2.push({ label: item.name, id: item.id });
            }
          });
        }
        //   可见权限
        rows.visibleUserIds.split(",").forEach(items2 => {
          if (item.id == items2) {
            arr3.push({ label: item.name, id: item.id });
          }
        });
      });
      let UserId2 = [];
      let UserId1 = [];
      let sss1 = [];
      let sss2 = [];
      arr2.forEach(elment => {
        sss2.push(elment.id);
        let item = this.getTreeIds(this.user, elment.id);
        UserId2.push(item);
      });
      arr3.forEach(elment => {
        sss1.push(elment.id);
        let item = this.getTreeIds(this.user, elment.id);
        UserId1.push(item);
      });
      this.formLabelAlign.UserId1 = UserId1;
      this.formLabelAlign.UserId2 = UserId2;
      this.formLabelAlign.assessorUserId1 = sss1;
      this.formLabelAlign.assessorUserId2 = sss2;
      this.sss1 = sss1;
      this.sss2 = sss2;
      console.log(this.formLabelAlign.UserId2, this.formLabelAlign.UserId1);
    },
    // 通过子节点ID查找所有关联的父节点
    getTreeIds(tree, nodeId, config) {
      const { children = "children", id = "value" } = config || {};
      const toFlatArray = (tree, parentId) => {
        return tree.reduce((t, _) => {
          const child = _[children];
          return [
            ...t,
            parentId ? { ..._, parentId } : _,
            ...(child && child.length ? toFlatArray(child, _[id]) : [])
          ];
        }, []);
      };
      const getIds = flatArray => {
        let ids = [nodeId];
        let child = flatArray.find(_ => _.value == nodeId);
        while (child && child.parentId) {
          ids = [child.parentId, ...ids];
          child = flatArray.find(_ => _.value === child.parentId);
        }

        return ids;
      };
      return getIds(toFlatArray(tree));
    },
    handleNodeClick1(data) {
      const result = [];
      for (let j = 0; j < data.length; j++) {
        result.push(data[j][data[j].length - 1]);
      }
      this.formLabelAlign.assessorUserId1 = Array.from(new Set(result));
    },
    handleNodeClick2(data) {
      const result = [];
      for (let j = 0; j < data.length; j++) {
        result.push(data[j][data[j].length - 1]);
      }
      this.formLabelAlign.assessorUserId2 = Array.from(new Set(result));
    },
    //单个权限的提交
    async sure() {
      console.log(this.formLabelAlign.assessorUserId1, this.sss1);
      console.log(this.formLabelAlign.assessorUserId2, this.sss2);
      this.listLoading = true;
      if (!this.oneQuanxianList.fileType) {
        let arr = [];
        arr.push(this.idsd);
        const assessorUserId1 = this.formLabelAlign.assessorUserId1;
        const assessorUserId2 = this.formLabelAlign.assessorUserId2;
        const params1 = {
          visibleUserIds: assessorUserId1.toString(),
          uploadUserIds: assessorUserId2.toString(),
          ids: this.idsd.toString(),
          fileIds: ""
        };
        const res = await kyDirectory(params1);
        if (res.code == 0) {
          this.$message({
            message: "权限设置成功",
            type: "success"
          });
          console.log(this.quanxianList);
          const res = await getTreeShuaxin({ id: this.oneQuanxianList.pid });
          if (res.code == 0) {
            if (res.data.children) {
              this.tableData = [...res.data.children, ...res.data.files];
            } else if (!res.data.children) {
              this.tableData = [...res.data.files];
            } else {
              this.tableData = [];
            }
          }
          this.formLabelAlign = {
            UserId1: [],
            UserId2: [],
            assessorUserId1: [],
            assessorUserId2: []
          };
          this.centerDialogVisible = false;
        } else {
          console.log(error);
        }
      } else {
        let arr = [];
        arr.push(this.idsd);
        const assessorUserId1 = this.formLabelAlign.assessorUserId1;
        const params1 = {
          visibleUserIds: assessorUserId1.toString(),
          uploadUserIds: "",
          ids: "",
          fileIds: this.idsd.toString()
        };
        const res = await kyDirectory(params1);
        if (res.code == 0) {
          this.$message({
            message: "权限设置成功",
            type: "success"
          });

          const res = await getTreeShuaxin({
            id: this.oneQuanxianList.directoryId
          });
          if (res.code == 0) {
            if (res.data.children) {
              this.tableData = [...res.data.children, ...res.data.files];
            } else if (!res.data.children) {
              this.tableData = [...res.data.files];
            } else {
              this.tableData = [];
            }
          }
          this.formLabelAlign = {
            UserId1: [],
            UserId2: [],
            assessorUserId1: [],
            assessorUserId2: []
          };
          this.centerDialogVisible = false;
        } else {
          console.log(error);
        }
      }
      this.listLoading = false;
    },
    close() {
      this.formLabelAlign = {
        UserId1: [],
        UserId2: [],
        assessorUserId1: [],
        assessorUserId2: []
      };
      //   this.idsd = [];
      this.centerDialogVisible = false;
    }
  }
};
</script>
  
<style lang="scss" scoped>
.app-container {
  height: 100%;
  display: flex;
  background-color: #f4f5fc;
  .data-tree,
  .data-main {
    padding: 12px 20px;
    border: 1px solid #dcdfe6;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
    background-color: #fff;
  }
  .data-tree {
    width: 350px;
    margin-right: 15px;
    overflow: auto;
    ::v-deep .el-tree {
      .el-tree-node {
        position: relative;
        padding-left: 16px; // 缩进量
      }
      > .el-tree-node {
        padding-left: 0; // 缩进量
      }
      .el-tree-node__children {
        padding-left: 16px; // 缩进量
      }
      // 竖线
      .el-tree-node::before {
        content: "";
        width: 1px;
        height: 100%;
        position: absolute;
        left: -4px;
        top: -15px;
        border-left: 1px dashed #52627c;
      }
      // 当前层最后一个节点的竖线高度固定
      .el-tree-node:last-child::before {
        height: 30px; // 可以自己调节到合适数值
      }
      // 横线
      .el-tree-node::after {
        content: "";
        width: 24px;
        height: 30px;
        position: absolute;
        left: -3px;
        top: 15px;
        border-top: 1px dashed #52627c;
      }

      // 去掉最顶层的虚线，放最下面样式才不会被上面的覆盖了
      & > .el-tree-node::after {
        border-top: none;
      }
      & > .el-tree-node::before {
        border-left: none;
      }

      // 展开关闭的icon
      .el-tree-node__expand-icon {
        // 叶子节点（无子节点）
        &.is-leaf {
          color: transparent;
          width: 0;
          // display: none; // 也可以去掉
        }
      }
    }
  }
  .data-main {
    flex: 1;
    overflow: auto;
  }
}
.el-divider--horizontal {
  margin: 12px 0 8px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 5px;
  overflow: hidden;
  .label {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .folder {
    width: 16px;
    height: 16px;
    margin-right: 8px;
    background: url("../../assets/static/folder.png") no-repeat;
    background-size: 100% 100%;
  }
}
::v-deep {
  .el-tree-node__content {
    height: 30px;
  }
  .el-tree-node.is-current > .el-tree-node__content {
    color: #3b95ff;
  }
}

.upload {
  display: inline-block;
  margin-left: 10px;
}
.dialog-footer {
  text-align: center;
}
</style>
  